package gold.digger;

import java.util.*;
import java.util.Arrays;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC648 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public String replaceWords(List<String> dictionary, String sentence) {
            Set<String> dict = new HashSet<>();
            for (String word : dictionary) {
                dict.add(word);
            }

            StringBuilder sb = new StringBuilder();
            String[] wordList = sentence.split(" ");
            for (String word : wordList) {
                boolean find = false;
                for (int i = 0; i < word.length(); i++) {
                    String subWord = word.substring(0, i + 1);
                    if (dict.contains(subWord)) {
                        sb.append(subWord).append(" ");
                        find = true;
                        break;
                    }
                }
                if (!find) sb.append(word).append(" ");
            }

            sb.delete(sb.length() - 1, sb.length());
            return sb.toString();
        }
    }

    public void run() {
        Solution solution = new Solution();

        String[] arr = {"cat", "bat", "rat"};
        String sentence = "the cattle was rattled by the battery";
        System.out.println(solution.replaceWords(Arrays.asList(arr), sentence));
    }

    public static void main(String[] args) throws Exception {
        LC648 an = new LC648();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
